package com.example.music

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log

class MusicService : Service() {

    companion object {
        const val Commond = "Operate"
    }
    private val TAG = "MusicService"               //声明tag标签方便调试


    private val mediaPlayer = MediaPlayer()
    private val musicList = mutableListOf<String>()
    private val musicNameList = mutableListOf<String>()
    private var current = 0                    //表示当前第几首歌
    private var isPause = false               //var可变变量
    private val binder = MusicBinder()

    //声明内部类
    inner class MusicBinder : Binder() {
//        fun musicName() = musicNameList[current]
        val musicName: String
            get() = musicNameList[current]
        var currentPosition: Int
            get() = mediaPlayer.currentPosition
            set(value) {
                mediaPlayer.seekTo(value)
            }

        val duration: Int
            get() = mediaPlayer.duration

        val size: Int
            get() = musicList.size

        var currentIndex: Int
            get() = current
            set(value) {
                // 确保在这里更新 `current` 的值
                this@MusicService.current = value
            }
    }

    override fun onCreate() {
        super.onCreate()
        getMusicList()
        // 函数回调
        mediaPlayer.setOnPreparedListener {
            it.start()
        }

        mediaPlayer.setOnCompletionListener {
            current++
            if (current >= musicList.size) {
                current = 0
            }
            play()
        }     // 设置监听器，当音乐播放完毕时，自动播放下一首
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Commond,1) ?: 1

        when(operate){
            1 -> {
                play()
            }
            2 -> {
                pause()
            }
            3 -> {
                stop()
            }
            4 -> {
                next()
            }
            5 -> {
                prev()
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }

    private fun stop() {
        mediaPlayer.stop()
        stopSelf()
    }

    private fun pause() {
        if (isPause) {
            mediaPlayer.start()
            isPause = false
        } else {
            mediaPlayer.pause()
            isPause = true
        }
    }

    fun next() {
        current++
        if (current >= musicList.size) {
            current = 0
        }
//        updateNotification(musicNameList[current])
        play()
    }

    private fun prev() {
        current--
        if (current < 0) {
            current = musicList.size - 1
        }
//        updateNotification(musicNameList[current])
        play()
    }

    private fun play() {
        if (musicList.isEmpty()) {
            Log.e(TAG, "play: Music list is empty!")
            return
        }
        val path = musicList[current]

//        if (binder.currentIndex != current) {
//            // 更新当前歌曲索引
//            binder.currentIndex = current
////            updateNotification(musicNameList[current])
//        }

        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()

        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun updateNotification(songName: String) {
        val Channel_ID = "my_channel"
        val Notification_ID = 1    // 通知id
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // 获取通知管理器
        val builder: Notification.Builder

        // 创建 NotificationChannel（仅适用于 Android O 及以上版本）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(Channel_ID, "Music Channel", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(notificationChannel)
            builder = Notification.Builder(this, Channel_ID)
        } else {      // 对于低于 Android O 的版本，使用旧的方式创建 Notification
            builder = Notification.Builder(this)
        }
        // 创建 Intent 和 PendingIntent
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val notification = builder.setSmallIcon(R.drawable.ic_new_music)
            .setContentTitle("Now Playing")
            .setContentText(songName)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        notificationManager.notify(Notification_ID, notification) // 发送/更新通知
    }


    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    private fun getMusicList() {
        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            MediaStore.Audio.Media.DEFAULT_SORT_ORDER
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val columnIndexData = cursor.getColumnIndex(MediaStore.Audio.Media.DATA)
                val columnNameData = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)

                if (columnIndexData >= 0 && columnNameData >= 0) {
                    val musicPath = cursor.getString(columnIndexData)
                    val musicName = cursor.getString(columnNameData)
                    musicList.add(musicPath)
                    musicNameList.add(musicName)
                    Log.d(TAG, "getMusicList: $musicPath name:$musicName")
                } else {
                    Log.e(TAG, "getColumnIndex returned an invalid index for columns: Data or Title")
                }
            }
            cursor.close()

            // 添加日志输出
            Log.d(TAG, "getMusicList: Music list size: ${musicList.size}")
        } else {
            Log.e(TAG, "Cursor is null after query.")
        }
    }
}